<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑账号' : '添加账号'"
    width="500px"
    :close-on-click-modal="false"
    @closed="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      label-position="top"
    >
      <el-form-item label="网站/应用名称" prop="title">
        <el-input
          v-model="form.title"
          placeholder="例如：GitHub、微信等"
          :prefix-icon="Operation"
        />
      </el-form-item>

      <el-form-item label="网站地址" prop="url">
        <el-input
          v-model="form.url"
          placeholder="https://www.example.com"
          :prefix-icon="Link"
        />
      </el-form-item>

      <el-form-item label="用户名/邮箱" prop="username">
        <el-input
          v-model="form.username"
          placeholder="用户名或邮箱地址"
          :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <div class="password-input-group">
          <el-input
            v-model="form.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            :prefix-icon="Key"
          />
          <el-button
            :icon="showPassword ? Hide : View"
            @click="showPassword = !showPassword"
          />
          <el-button
            type="primary"
            :icon="Refresh"
            @click="showPasswordGenerator = true"
          >
            生成
          </el-button>
        </div>
        
        <!-- 密码强度指示器 -->
        <div v-if="form.password" class="password-strength">
          <div class="strength-bar">
            <div 
              class="strength-fill" 
              :class="strengthClass"
              :style="{ width: strengthWidth }"
            ></div>
          </div>
          <span class="strength-text" :class="strengthClass">
            {{ strengthText }}
          </span>
        </div>
      </el-form-item>

      <el-form-item label="分类" prop="category">
        <el-select
          v-model="form.category"
          placeholder="选择分类"
          style="width: 100%"
          allow-create
          filterable
          default-first-option
        >
          <el-option
            v-for="category in allCategories"
            :key="category"
            :label="category"
            :value="category"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.notes"
          type="textarea"
          :rows="3"
          placeholder="可选，添加一些备注信息"
        />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="form.isFavorite">
          添加到收藏夹
        </el-checkbox>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          :loading="saving"
          @click="handleSave"
        >
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>

    <!-- 密码生成器对话框 -->
    <PasswordGenerator
      v-model="showPasswordGenerator"
      mode="dialog"
      @generated="handlePasswordGenerated"
    />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage } from 'element-plus'
import {
  Operation, Link, User, Key, Refresh, View, Hide
} from '@element-plus/icons-vue'
import PasswordGenerator from './PasswordGenerator.vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  account: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'saved'])

const accountsStore = useAccountsStore()

// 加载自定义分类
const loadCustomCategories = () => {
  try {
    const saved = localStorage.getItem('customCategories')
    if (saved) {
      return JSON.parse(saved)
    }
  } catch (error) {
    console.error('加载自定义分类失败:', error)
  }
  return []
}

// 所有可用分类
const allCategories = computed(() => {
  const customCategories = loadCustomCategories()
  const customCategoryNames = customCategories.map(cat => cat.name)
  return [...accountsStore.categories, ...customCategoryNames]
})

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref()
const saving = ref(false)
const showPassword = ref(false)
const showPasswordGenerator = ref(false)

const isEdit = computed(() => !!props.account)

const form = reactive({
  title: '',
  url: '',
  username: '',
  password: '',
  category: '个人',
  notes: '',
  isFavorite: false
})

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入网站/应用名称', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 1, message: '密码不能为空', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
})

// 密码强度计算
const passwordStrength = computed(() => {
  const password = form.password
  if (!password) return 0

  let score = 0
  
  // 长度评分
  if (password.length >= 8) score += 1
  if (password.length >= 12) score += 1
  
  // 字符类型评分
  if (/[a-z]/.test(password)) score += 1
  if (/[A-Z]/.test(password)) score += 1
  if (/[0-9]/.test(password)) score += 1
  if (/[^a-zA-Z0-9]/.test(password)) score += 1
  
  return Math.min(score, 5)
})

const strengthWidth = computed(() => `${(passwordStrength.value / 5) * 100}%`)

const strengthClass = computed(() => {
  const strength = passwordStrength.value
  if (strength <= 1) return 'weak'
  if (strength <= 2) return 'fair'
  if (strength <= 3) return 'good'
  if (strength <= 4) return 'strong'
  return 'very-strong'
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength <= 1) return '很弱'
  if (strength <= 2) return '较弱'
  if (strength <= 3) return '一般'
  if (strength <= 4) return '较强'
  return '很强'
})

// 监听账号数据变化，用于编辑模式
watch(() => props.account, (account) => {
  if (account) {
    Object.assign(form, {
      title: account.title || '',
      url: account.url || '',
      username: account.username || '',
      password: account.password || '',
      category: account.category || '个人',
      notes: account.notes || '',
      isFavorite: account.isFavorite || false
    })
  }
}, { immediate: true })

// 处理密码生成
const handlePasswordGenerated = (password) => {
  form.password = password
  showPasswordGenerator.value = false
  ElMessage.success('密码已生成')
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    saving.value = true
    
    const accountData = {
      title: form.title.trim(),
      url: form.url.trim(),
      username: form.username.trim(),
      password: form.password,
      category: form.category,
      notes: form.notes.trim(),
      isFavorite: form.isFavorite
    }
    
    if (isEdit.value) {
      await accountsStore.updateAccount(props.account.id, accountData)
    } else {
      await accountsStore.addAccount(accountData)
    }
    
    emit('saved')
  } catch (error) {
    if (error.fields) {
      // 表单验证错误，不需要显示消息
      return
    }
    console.error('保存账号失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 处理对话框关闭
const handleClose = () => {
  if (!isEdit.value) {
    // 新增模式下清空表单
    Object.assign(form, {
      title: '',
      url: '',
      username: '',
      password: '',
      category: '个人',
      notes: '',
      isFavorite: false
    })
  }
  showPassword.value = false
  
  // 清除表单验证状态
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
</script>

<style scoped>
.password-input-group {
  display: flex;
  gap: 8px;
}

.password-input-group .el-input {
  flex: 1;
}

.password-strength {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.strength-bar {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.strength-fill {
  height: 100%;
  border-radius: 2px;
  transition: all 0.3s ease;
}

.strength-fill.weak {
  background: #f56c6c;
}

.strength-fill.fair {
  background: #e6a23c;
}

.strength-fill.good {
  background: #409eff;
}

.strength-fill.strong {
  background: #67c23a;
}

.strength-fill.very-strong {
  background: #13ce66;
}

.strength-text {
  font-size: 12px;
  font-weight: 500;
  min-width: 40px;
}

.strength-text.weak {
  color: #f56c6c;
}

.strength-text.fair {
  color: #e6a23c;
}

.strength-text.good {
  color: #409eff;
}

.strength-text.strong {
  color: #67c23a;
}

.strength-text.very-strong {
  color: #13ce66;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
